package com.example.employeemanagement.Controller;


import com.example.employeemanagement.dto.GetEmployeeById;
import com.example.employeemanagement.dto.InfoDto;
import com.example.employeemanagement.entry.Employee;
import com.example.employeemanagement.service.EmployeeService;
import com.example.employeemanagement.vo.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

// 员工
@RestController
@RequestMapping("/employees")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;


    @GetMapping
    public List<Employee> getAllEmployees() {
        return employeeService.getAllEmployees();
    }

    @PostMapping
    public String addEmployee(@RequestBody Employee employee) {
        return employeeService.addEmployee(employee);
    }

    @GetMapping("/{id}")
    public Optional<GetEmployeeById> getEmployeeById(@PathVariable Integer id) {
        return employeeService.getEmployeeById(id);
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<?>> updateEmployee(@PathVariable Integer id, @RequestBody Employee updatedEmployee) {
        String msg= employeeService.updateEmployee(id, updatedEmployee);
        ApiResponse<?> response = new ApiResponse<>("SUCCESS", msg, null);
        return ResponseEntity.ok(response);
    }

    @DeleteMapping("/{id}")
    public String deleteEmployee(@PathVariable Integer id) {
        return employeeService.deleteEmployee(id);
    }

    @GetMapping("/info")
    public ResponseEntity<ApiResponse<InfoDto>> getUserInfo(@RequestHeader("Authorization") String authHeader) {
        try {
            // 从Authorization头中提取token
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                throw new IllegalArgumentException("无效的Authorization头");
            }

            String token = authHeader.substring(7); // 去掉"Bearer "前缀

            // 获取用户信息
            InfoDto userInfo = employeeService.getEmployeeInfo(token);

            // 构建成功响应
            ApiResponse<InfoDto> response = new ApiResponse<>("SUCCESS", "获取当前用户信息成功", userInfo);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            // 构建错误响应
            ApiResponse<InfoDto> response = new ApiResponse<>("ERROR", e.getMessage(), null);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        } catch (Exception e) {
            // 构建系统错误响应
            System.out.println("info接口存在问题"+e);
            ApiResponse<InfoDto> response = new ApiResponse<>("ERROR", "系统错误，请稍后重试", null);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}